﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

//Author  : Shantha Kumar .T
//Blog    : http://www.ktskumar.com
//Twitter : http://twitter.com/ktskumar
//Facebook: http://www.facebook.com


namespace SPConsole.DownloadDocument
{
    class Program
    {
        static void Main(string[] args)
        {

            //Copy WebService Settings
            string webUrl = "http://localhost";
            
            WSCopy.Copy copyService = new WSCopy.Copy();
            copyService.Url = webUrl+"/_vti_bin/copy.asmx";

            //Pass the Current User Credentials to the WebService
            copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            //Pass the Custom User Credential to the WebService
            //copyService.Credentials = System.Net.CredentialCache.NetworkCredential("UserName", "Password", "Domain");

            //Source and Destination Document URLs
            string sourceUrl = "http://localhost/Shared Documents/Sample.doc";
            string destinationUrl = "E:\\DocumentsSample.doc";

            //Variables for Reading metadata’s of a document
            WSCopy.FieldInformation fieldInfo = new WSCopy.FieldInformation();
            WSCopy.FieldInformation[] fieldInfoArray = { fieldInfo };
            WSCopy.CopyResult cResult1 = new WSCopy.CopyResult();
            WSCopy.CopyResult cResult2 = new WSCopy.CopyResult();
            WSCopy.CopyResult[] cResultArray = { cResult1, cResult2 };

            //Receive a Document Contents  into Byte array (filecontents)
            byte[] fileContents = new Byte[4096];
            uint copyresult = copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);

            if (copyresult == 0)
            {
                Console.WriteLine("Document downloaded Successfully, and now it's getting saved in location " + destinationUrl);

                //Create a new file and write contents to that document
                FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
                fStream.Write(fileContents, 0, fileContents.Length);
                fStream.Close();

            }
            else
            {
                Console.WriteLine("Document Downloading gets failed...");
            }

            Console.Write("Press any key to exit...");
            Console.Read();

            
        }
    }
}
